package com.xiaoy.javamaildemo.formwork.javamail;

import com.xiaoy.javamaildemo.JavaMailConf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.util.Assert;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * @ClassName MailFactory
 * @Description TODO
 * @Author xiaoying
 * @Date 2022/6/27 13:56
 * @Version V1.0.0
 */
@Slf4j
public class MailFactory {

    public static IMail createContext(JavaMailConf javaMailConf){

        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = javaMailConf.getUserName();
                String password = javaMailConf.getPassword();
                return new PasswordAuthentication(userName, password);
            }
        };
        return createProxyBean(javaMailConf,authenticator);
    }

    private static IMail createProxyBean(JavaMailConf javaMailConf, Authenticator authenticator){
        Enhancer enhancer = new Enhancer();
        enhancer.setCallback(new MailInvocationHandler());
        enhancer.setInterfaces(new Class[]{IMail.class});
        enhancer.setSuperclass(MailContext.class);
        IMail o = (IMail) enhancer.create(new Class[]{JavaMailConf.class,Authenticator.class}, new Object[]{javaMailConf,authenticator});
        return o;
    }

//    private static MailConfDO findMailConf(String sendAddress) {
//        MailConfService mailConfService = (MailConfService) ApplicationContextHelper.getApplicationContext().getBean("mailConfServiceImpl");
//        MailConfDO mailConfDO = mailConfService.queryAllByShopMail(sendAddress);
//        Assert.isTrue(null != mailConfDO,"sendAddress:"+sendAddress+"not match MailConf");
//        return mailConfDO;
//    }

}
